package com.cml.dm.admin.service.sql;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cml.dm.admin.entity.DmExeLogger;
import com.cml.dm.admin.entity.DmMetadata;
import com.cml.dm.admin.service.RecoverySqlGenerateService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class DefaultRecoverySqlGenerateService implements RecoverySqlGenerateService {
    @Override
    public List<String> sqlGenerate(DmMetadata dmMetadata, DmExeLogger dmExeLogger, Object extParameter) {
        List<String> sqlList = new ArrayList<>();
        Map<String, JSONObject> dataMap = (Map<String, JSONObject>) extParameter;
        JSONObject jsonObject = dataMap.get(dmMetadata.getNodeId());
        JSONArray datas = jsonObject.getJSONArray("data");
        StringBuilder sb = new StringBuilder();
        sb.append(dmMetadata.getRecoverySql());
        int len = datas.size();
        String sql = null;
        Object val = null;
        for(int i = 0; i< len; i++){
            JSONObject data = datas.getJSONObject(i);
            sql = sb.toString();

            for(String key : data.keySet()){
                val = data.get(key);
                if(null == val) {
                    sql = sql.replace("${"+key+"}", "null");
                    continue;
                }
                if((val.toString().indexOf("-")>0 && val.toString().length() == 10)
                   || (val.toString().indexOf(":")>0 && val.toString().length() == 19)
                   || val.getClass().getSimpleName().equals("String")
                ){
                    //如果是日期
                    sql = sql.replace("${"+key+"}", "'"+data.getString(key)+"'");
                    continue;
                }
                sql = sql.replace("${"+key+"}", data.getString(key));
            }
            sqlList.add(sql);
        }
        return sqlList;
    }
}
